package com.iLoo.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("preHandle拦截的请求路径是{}",requestURI);

        //登录检查逻辑
        Object user = request.getServletContext().getAttribute("user");

        if(user != null){
            //放行
            return true;
        }

        //拦截住。未登录。跳转到登录页
        //request.getServletContext().setAttribute("msg","请先登录2");


        //request.setAttribute("msg","请先登录");

        //response.sendRedirect("/login");
        //因为用转发，路径不会变，太难看了，所以想重定向，
        //但是他这里用转发是因为重定向的话request信息就传不过去了
        //经测试= -、只能这样了，难看就难看吧
        //request.getRequestDispatcher("/login").forward(request,response);

        //还有第二趟方案，就是用session来存数据，然后重定向
        //但是前后端分离的时候应该就不能用了，但先不管他！
        //想想又能用ServletContext
        //好吧，经测试，ServletContext可以

        request.getServletContext().setAttribute("msg","请先登录");
        //session.setAttribute("msg","session处理请先登录");
        response.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
